<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use think\exception\ValidateException;
use think\Exception;
use app\common\validate\Category as CategoryValidate;
use app\common\model\content\Category as CategoryModel;
use think\facade\Log;

/**
 * #分类管理控制器
 * Class Category
 * @package app\admin\controller
 */
class Category extends BaseController
{

    //是否关联user模型( 用于权限规则验证 )
    public $relateUser = true;

    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list','save','update','del','delBatch']],
    ];

    //列表展示
    public function index(){
        return view('category/index');
    }


    //列表数据
    public function list(){
        try{
            //获取列表数据
            $data = CategoryModel::getListData($this->ruleWhere());


        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage(),
            ]);
        }

        //成功返回
        return json([
            'code'  => 0,
            'msg'=> '查询列表成功',
            'count' => $data['count'],
            'data'  => $data['data']
        ]);

    }

    //添加**
    public function add(){
        //渲染页面
        return view('category/add');
    }

    public function save(){
        //处理post表单
        return $this->postHandle($this->getModel(CategoryModel::class),'添加分类成功.','添加分类失败.');
    }

    //修改
    public function edit(int $id){
        //获取模型
        $model = $this->getModel(CategoryModel::class,$id);
        return view('category/edit',[
            'model' => $model
        ]);
    }

    public function update(int $id){
        //获取模型
        $model = $this->getModel(CategoryModel::class,$id);
        return $this->postHandle($model, '修改分类成功.','修改分类失败');
    }

    //删除
    public function del(int $id){
        //获取模型
        $model = $this->getModel(CategoryModel::class,$id);
        try{

            if ($model->delete() === false){
                throw new Exception('删除分类失败.');
            }

        }catch (\Exception $e){
            //Log::error($this->request->completePathInfo(true) . ' : ' .$e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        //删除成功
        return json(['code'=>0,'msg'=>'删除分类成功']);
    }

    //批量删除
    public function delBatch(){
        try{
            $ids = explode(',',trim(request()->param('ids'),','));

            if( $this->batchRule(CategoryModel::class, (array) $ids) &&
                CategoryModel::destroy($ids) === false )
            {
                throw new Exception('批量删除分类失败.');
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }

        return json([
            'code' => 0,
            'msg' => '批量删除分类成功.'
        ]);

    }



    //处理表单
    private function postHandle(CategoryModel $model, string $successMsg, string $failMsg){

        try{
            $data = array_merge(request()->only(['name','desc']), ['id'=>$model->id]);

            validate(CategoryValidate::class)->check($data);

            if( !$model->save($data) )
                throw new Exception($failMsg);

        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }

        //添加成功
        return json(['code'=>0,'msg'=>$successMsg]);

    }
}